﻿using MiniJob;
using MiniJob.RestClient;
using MiniJob.Service;

namespace Microsoft.AspNetCore.Builder;

public static class ServiceCollectionExtensions
{
    public static WebApplicationBuilder UseMiniJob(this WebApplicationBuilder builder)
    {
        Global.Config = builder.Configuration;
        builder.UseMiniJobOrleans();
        builder.Services.AddMiniJob(builder.Configuration);

        return builder;
    }

    public static void AddMiniJob(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddGuidGenerator();
        services.AddHttpClient(Global.DefaultHttpClientName)
            .ConfigurePrimaryHttpMessageHandler(() => NewMessageHandler(true));
        services.AddScoped<IRestClient, DefaultRestClient>();
        services.AddFreeSql(configuration);
        services.AddHostedService<InitService>();

        services.AddScoped<IAppService, AppService>();
        services.AddScoped<IJobService, JobService>();
        services.AddScoped<IDataSeedService, DataSeedService>();
        services.AddScoped<IScheduleTaskManager, ScheduleTaskManager>();
    }

    static HttpClientHandler NewMessageHandler(bool alwaysTrustSsl)
    {
        var handler = new HttpClientHandler();
        if (alwaysTrustSsl)
        {
            handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
        }

        return handler;
    }
}
